package tbdp.tool;

import com.google.common.base.Preconditions;
import net.iryndin.jdbf.core.DbfField;
import net.iryndin.jdbf.core.DbfMetadata;
import net.iryndin.jdbf.core.DbfRecord;
import net.iryndin.jdbf.reader.DbfReader;
import tbdp.tool.common.Utils;
import tbdp.tool.common.ZipUtil;

import java.io.File;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by xbkaishui on 16/10/16.
 * dbf 文件读取工具
 */
public class DBFReader {

    /**
     * 读取dbf文件内容 , 返回的是 dbf里面的每一行的内容
     *
     * @param file
     * @param charset
     * @return
     */
    public static List<Map<String, String>> readDbfFile(File file, String charset) {
        Charset cs = Charset.forName(charset);
        List<Map<String, String>> result = new LinkedList<>();
        File realFile = file;
        try {
            //判断是不是zip文件
            if (file.getName().endsWith(".zip")) {
                List<File> fileList = ZipUtil.decompress(file);
                Preconditions.checkArgument(fileList.size() == 1, "zip文件里面文件个数多于一个" + fileList);
                realFile = fileList.get(0);
            }

            DbfRecord rec;
            try (DbfReader reader = new DbfReader(realFile)) {
                DbfMetadata meta = reader.getMetadata();
//                System.out.println("Read DBF Metadata: " + meta);
                while ((rec = reader.read()) != null) {
                    Map<String, String> record = new LinkedHashMap<>();
                    rec.setStringCharset(cs);
                    for (DbfField f : rec.getFields()) {
                        String name = f.getName();
                        String value = rec.getString(name, cs);
                        if(value != null){
                            record.put(name, value.trim());
                        }
                    }
                    result.add(record);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(file.getAbsolutePath(), e);
        } finally {
            Utils.deleteFilesOnExit(realFile);
        }
        return result;
    }

    public static List<Map<String, String>> readDbfFile(String file, String charset) {
        return readDbfFile(new File(file), charset);
    }

}
